'use strict';
var YX = function(accid) {
  this.accid = accid;
  this.departOpers = [];
  this.initModule();
  this.cache = new Cache();
  this.mysdk = new SDKBridge(this, this.cache);
  if (window.nim) {
    // this.myNetcall = new NetcallBridge(this);
    this.myNetcall = {}
  }
  this.firstLoadSysMsg = true;
  this.totalUnread = 0;

  //常用语模块数据
  this.commonWordsList = [];
  this.haveInHandConsultId = "";
  this.otherAccid = "";
  this.tuWenTimes = 0;

};
YX.fn = YX.prototype;

//初始化各模块数据
YX.fn.initModule = function() {//法律咨询模块下面几个模块信息无需获取
  this.initBase();
  this.message();
  this.notification();
  this.personCard();
  // this.sysMsg();
  this.session();
  // this.friend();
  // this.team();
  this.cloudMsg();
  // this.createTeamImfo();
  // this.caseCenter();
  setTimeout(()=>{
    if(window.location.search){
      let toAccount = window.location.search.split("=")[1];
      var options = {
        scene: 'p2p',
        to: toAccount,
        text: "您好!",
        done: this.sendMsgDone.bind(this)
      };
      this.nim.sendText(options);
      this.openChatBox(toAccount,'p2p')
    }
  },1500)
};
YX.fn.initBase = function() {
  // 初始化节点事件
  this.$mask = $('#mask');
  //左上角信息
  this.$userPic = $('#userPic');
  this.$userName = $('#userName');
  // this.$iMmobileNo = $('#iMmobileNo');
  this.$lawyerFirmName = $('#lawyerFirmName');
  //右边面板内容节点
  this.$rightPanel = $('#rightPanel');
  this.$chatTitle = $('#chatTitle');
  this.$chatContent = $('#chatContent');
  this.$nickName = $('#nickName');
  this.$memberNum = $('#memberNum');
  //切换面板
  this.$switchPanel = $('#switchPanel');
  this.$switchPanel.on('click', 'a', this.switchPanel.bind(this));
  //切换的面板
  this.$sessionsWrap = $('#sessionsWrap');
  this.$friendsWrap = $('#friendsWrap');
  this.$teamsWrap = $('#teamsWrap');
  this.$panelItems = $('#left-panel .item');

  // 截图
  this.$fireflyScreenShot = $('#fireflyScreenShot');
  this.$fireflyScreenShot.on('click',this.fireflyScreenShot.bind(this));
  //2面板中间的圆点
  // this.$chatVernier = $('#chatVernier span');
  // $('#left-panel .item .list').on('scroll', this.doPoint.bind(this));
  //登出
  this.logoutEvt();
  //获取mis系统人员关系
  // this.getdepartOper();
  //多端登陆
  this.multiportEvt();
};

//截图
YX.fn.fireflyScreenShot = function(){
  var captureRet = Capture(false);
  // console.log("captureRet==",captureRet)
  // console.log("emCaptureFailed==",emCaptureFailed)
    //从返回值来解析显示  	
  if(captureRet == '8'){		
        this.capturePopUp();
    }else if(captureRet == emCaptureUnknown){
        ShowDownLoad();
	}else if(captureRet == emCaptureFailed){
        ShowDownLoad();
  }
  
}

//弹框提示
YX.fn.capturePopUp = function(){
    var text = "请先调整您的窗口,将需要截取的内容显示在屏幕的可见区域。";
    layer.open({
      type: 1,
      title:"准备截屏",
      content: '<div style="padding: 20px">'+ text +'</div>',
      btn: '开始截图',
      btnAlign: 'c', //按钮居中
      shade: 0 ,//不显示遮罩
      yes: function(){
        layer.closeAll();
        setTimeout(function(){
          var captureRet = Capture(true);
          if(captureRet == emCaptureSuccess){		
            console.log("正在截图中")
          }else if(captureRet == emCaptureUnknown){
              ShowDownLoad();
          }else if(captureRet == emCaptureFailed){
                ShowDownLoad();
          }
        },200);
      }
    });
}



// 桌面消息提醒
YX.fn.sysDesktopMsgTip = function(msg){
  console.log("桌面发来的消息=======",msg)
  var that = this;
  var teamList = this.cache.getTeamlist();
  var teamName = "";
  for(var i=0;i<teamList.length;i++){
    if(teamList[i].teamId == msg.target){
      teamName = teamList[i].name
      break;
    }
  }
  if (window.Notification) {
    var popNotice = function() {
        if (Notification.permission == "granted") {
          var textMsg = buildSessionMsg(msg);
          
            // if(msg.type == "image" || msg.type == "video" || msg.type == "geo" || msg.type == "file"){
            //   textMsg = msg.pushContent
            // }
            if(msg.type == 'text' && textMsg.indexOf("<img") != '-1'){
              textMsg = msg.text;
            }
            var userInfo = that.cache.getUserById(msg.target);
            // info.nick = this.getNick(msg.target);
            let avatar = getAvatar(userInfo.avatar);
            var notification = new Notification("", {
                icon: avatar?avatar:"images/default-icon.png",  
                body: msg.fromNick+":"+textMsg,
                silent:true,
                sound:"audio/yinpin.mp3"
            });
            
            notification.onclick = function() {
                window.focus();
                notification.close();
                //打开聊天面板
                that.openChatBox(msg.target,'p2p')
            };
            setTimeout(function(){
                notification.close();
            },4000);
        }    
    };
    if (Notification.permission == "granted") {
        popNotice();
    } else if (Notification.permission != "denied") {
        Notification.requestPermission(function (permission) {
            popNotice();
        });
    }
  
  } else { 
    layer.msg("浏览器不支持Notification",{icon:5})   
  }
}

/**
 * 同步完成后 UI显示  本demo这里显示最近会话列表 跟消息中心 新系统通知技术计数
 * @see session.js
 */
YX.fn.initUI = function() {
  this.buildSessions();
  // this.showSysMsgCount();
};
/**
 * 初始化部门人员数据
 */
YX.fn.getdepartOper = function() {
  var departOpers=[],This=this;
  //获取内部用户
  firefly_IM_request.getRequest("get","/firefly-erp/depts",{},function(data){
    // console.log("查询内部部门列表=",data)
    if(data.isSuccess == "T"){
      let departList = data.body;
      departList.forEach(function (item,index) {
          departOpers.push({
            id:'dept'+item.deptId,
            level:item.level,
            title:item.deptName,
            parentId:item.parentId?'dept'+item.parentId:0,
            basicData:{isDept:true}
          })
      })
    }
    firefly_IM_request.getRequest("get","/firefly-erp/operInfos",{},function(data){
        // console.log("查询内部用户列表=",data)
        if(data.isSuccess == "T"){
          let operList = data.body;
          operList.forEach(function (item,index) {
            if(item.accId){
              departOpers.push({
                id:item.operId,
                title:item.realName,
                parentId:'dept'+item.deptId,
                accId:item.accId,
                deptName:item.deptName,
                checkArr:[{"type": "0", "isChecked": "0"}],
                basicData:{isDept:false},
                avatar:item.avatar
              })
            }
          })
          This.departOpers=departOpers
        }
    },function(data){
  
    });
  },function(data){

  });
  
};
/**
 * 初始化个人信息回调 显示左上角信息
 */
YX.fn.showMe = function() {
  //关闭加载层
  layer.closeAll('loading')
  console.log("渲染结束时间=",new Date().getTime())

  var user = this.cache.getUserById(userUID);
  this.$userName.text(user.nick);
  this.$userPic.attr('src', getAvatar(user.avatar));
  
  var iMmobileNo = sessionStorage.getItem("iMmobileNo");
  if(iMmobileNo && iMmobileNo != 'undefined'){
    iMmobileNo = iMmobileNo.substr(0,3)+"****"+iMmobileNo.substr(7,4)
  }
  this.$lawyerFirmName.text(sessionStorage.getItem('lawyerFirmName')?sessionStorage.getItem('lawyerFirmName'):iMmobileNo)
  // console.log("=============",user)
  // this.$iMmobileNo.text(iMmobileNo);
  sessionStorage.setItem('nickName', user.nick);
  sessionStorage.setItem('avatar', user.avatar);
};
/*********************************************
 * SDK初始化结束后，拉取需要用到的用户信息，群组信息
 *********************************************/
YX.fn.initInfo = function(obj, team) {
  this.lockPerson = true;
  this.lockTeam = true;
  var array = Object.keys(obj),
    teamArray = [];
  for (var i = team.length - 1; i >= 0; i--) {
    if (!this.cache.hasTeam(team[i])) {
      teamArray.push(team[i]);
    }
  }
  if (teamArray.length > 0) {
    this.mysdk.getLocalTeams(teamArray, this.cbInitLocalTeamInfo.bind(this));
  } else {
    this.lockTeam = false;
  }
  this.mysdk.getUsers(array, this.cbInitInfo.bind(this));
};
YX.fn.cbInitInfo = function(error, data) {
  if (!error) {
    this.cache.setPersonlist(data);
    this.lockPerson = false;
    if (this.lockTeam === false) {
      this.initUI();
    }
  } else {
    layer.msg("获取用户信息失败",{icon:2})
  }
};

YX.fn.cbInitLocalTeamInfo = function(err, data) {
  if (!err) {
    this.cache.addTeamMap(data.teams);
    this.lockTeam = false;
    if (this.lockPerson === false) {
      this.initUI();
    }
  } else {
    layer.msg("获取本地群组失败",{icon:2})  
  }
};

/*********************************
 * 点击左边面板，打开聊天框
 *********************************/
YX.fn.openChatBox = function(account, scene) {
  showChatImageList = new Array();//清空缓存图片信息

  console.log("账号==",account)
  console.log("环境==",scene)
  this.otherAccid = account;
  $("#noSelectChat").addClass('hide');//去掉未选择聊天记录的图层
  // $("#createNoTeamContainer").addClass('hide')
  // $('#createNoCaseContainer') && $('#createNoCaseContainer').addClass('hide');//未选择案件聊天窗口
  // $('#case-info-container') && $('#case-info-container').addClass('hide');


  //获取对应订单详情
  if(YX.fn.serveceConsultTime){
    clearInterval(YX.fn.serveceConsultTime)
  }
  $(".zx-time-cutdown").addClass("hide")
  $(".orderTips").addClass('hide')
  this.getOrderDet(account);



  // 切换聊天对象取消之前的语音播放以及录音
  YX.fn.stopPlayAudio()
  YX.fn.cancelRecordAudio()
  var info;
  var that = this;
  this.crtSession = scene + '-' + account;
  this.crtSessionType = scene;
  this.crtSessionAccount = account;
  this.mysdk.setCurrSession(scene, account);
  
  //隐藏其他窗口
  // $('#createTeamContainer') && $('#createTeamContainer').addClass('hide');
  // $('#teamInfoContainer') && $('#teamInfoContainer').addClass('hide');
  // $('#relevanceCaseContainer') && $('#relevanceCaseContainer').addClass('hide');
  // this.$devices && this.$devices.addClass('hide');
  $(".far-right-panel .far-right-tools").addClass("hide")
  $(".far-right-panel .far-right-order").removeClass("hide")
  

  this.$cloudMsgContainer && this.$cloudMsgContainer.addClass('hide');
  //退群的特殊UI
  this.$rightPanel.find('.u-chat-notice').addClass('hide');
  this.$rightPanel.find('.chat-mask').addClass('hide');
  this.$rightPanel.removeClass('hide');
  this.$messageText.val('');
  $('#showTeamMsgReceipt').hide()

  // 让netcall.js感知到打开聊天框的操作，做一些UI层的控制
  // this.myNetcall && this.myNetcall.whenOpenChatBox(scene, account);
  if (this.WB) this.WB.checkSession();
  // 是否是群管理员
  this.cache.isCurSessionTeamManager = false;
  //根据帐号跟消息类型获取消息数据
  if (scene == 'p2p') {
    info = this.cache.getUserById(account);
    this.$memberNum.text("");
    $("#headImg").removeClass("hide");
    $("#yhcHeaderImg").addClass("hide");
    if (info.account == userUID) {
      this.$nickName.text('我的手机');
      $("#headImg").attr('src', 'images/myPhone.png');
    } else {
      if (window.CONFIG.openSubscription) {
        var multiPortStatus = this.cache.getMultiPortStatus(account);
        if (multiPortStatus) {
          this.$nickName.text(
            this.getNick(account) + ' [' + multiPortStatus + ']'
          );
        } else {
          this.$nickName.text(this.getNick(account) + ' [离线]');
        }
      } else {
        this.$nickName.text(this.getNick(account));
      }
      $("#headImg").attr('src', getAvatar(info.avatar));
    }
    // 群资料入口隐藏
    this.$teamInfo && this.$teamInfo.addClass('hide');
  } else {
    //群聊
    info = this.cache.getTeamById(account);
    this.$teamInfo && this.$teamInfo.removeClass('hide');
    console.log("打开群组面板消息=",info)
    if (info) {
      // if (info.avatar) {
      //   this.$chatTitle
      //     .find('img')
      //     .attr('src', info.avatar + '?imageView&thumbnail=80x80&quality=85');
      // } else {
      //   this.$chatTitle.find('img').attr('src', 'images/' + info.type + '.png');
      // }
      // console.log("==========",info)
      var teamNameKey = "赢"
      if(info.serverCustom){
         teamNameKey = JSON.parse(info.serverCustom).teamNameKey;
        teamNameKey = teamNameKey?teamNameKey:"赢";
      }
      $("#headImg").addClass("hide");
      $("#yhcHeaderImg").removeClass("hide").text(teamNameKey)
      this.$nickName.text(info.name);
      this.$memberNum.text("( "+info.memberNum+" )");
    } else {
      // this.$rightPanel.find('.u-chat-notice').removeClass('hide');
      // this.$rightPanel.find('.chat-mask').removeClass('hide');
      // this.$chatTitle.find('img').attr('src', 'images/normal.png');
      // this.$nickName.text(account);
    }
    this.getTeamMembers(account, function() {
      that.cache.isCurSessionTeamManager = that.cache.isTeamManager(
        userUID,
        that.crtSessionAccount
      );
    });
    this.crtSessionTeamType = info ? info.type : 'normal';
    if (this.crtSessionTeamType === 'advanced') {
      $('#showTeamMsgReceipt').show();
    }
  }
  // this.doPoint();
  // 根据或取聊天记录
  this.getHistoryMsgs(scene, account);
};

/**
 * 切换左边面板上方tab
 */
YX.fn.switchPanel = function(evt) {
  var node;
  // console.log("node=====",evt)
  if (evt.target.tagName.toLowerCase() === 'span') {
    node = evt.target.parentNode;
  } else {
    node = evt.target;
  }
  $('.panel_tab').removeClass('cur');
  $(node).addClass('cur');
  var type = $(node).data('type');
  // this.$chatVernier.addClass('hide');
  $('.item[data-type="' + type + '"]')
    .removeClass('hide')
    .siblings('.item')
    .addClass('hide');
  if (type === 'sessions') {
    if($("#rightPanel").hasClass("hide")){
      $("#noSelectChat").removeClass("hide")
    }else{
      $("#noSelectChat").addClass("hide")
    }
    this.buildSessions();
  } else if (type === 'friends') {
    this.buildFriends();
  } else if(type === 'casecenter'){
    //清空所有显示层只显示空案件
    if($("#rightPanel").hasClass("hide")){
      $("#createNoCaseContainer").removeClass("hide")
    }else{
      $("#createNoCaseContainer").addClass("hide")
    }
    //调用案件中心模块
    this.getCaseList();
  }else {
    if($("#rightPanel").hasClass("hide")){
      $("#createNoTeamContainer").removeClass("hide")
    }else{
      $("#createNoTeamContainer").addClass("hide")
    }
    this.buildTeams();
  }
};




//p2p获取订单服务
YX.fn.getOrderDet = function(account){
  let accid = this.accid;
  var bodyInfo = {
    accidOne:accid,
    accidTwo:account
  }
  $(".far-right-panel .far-order-info").html("")
  let _that = this;
  firefly_IM_request.getRequest("get","/lawyerService/recent",bodyInfo,function(res){
      console.log("订单详情====",res)
      if(res.isSuccess == "T" && res.body){
        _that.haveInHandConsultId = res.body.id;
        $("#nickName").text(res.body.userName)
        if(res.body.serviceStatus == 3){//表示合作中
          $(".zx-time-cutdown").removeClass('hide')
          $("#endserviceBtn").removeClass("hide")
          let str = `
                  <div class="order-items">
                    <div class="title-top">
                      <img src="./images/flzx/u-custom-pic102.png" alt="">
                      <span class="top-tw">${lawyerServiceSubTypeEnum[res.body.lawyerServiceSubType]}</span>
                      <span class="top-hy">${lawyerServiceSmallTypeEnum[res.body.serviceType]}</span>
                    </div>
                    <div class="result-desc">${res.body.serviceDesc}</div>
                    <div class="order-oth">
                      <div class="order-oth-item">
                        <span>咨询者</span>${res.body.userName}
                      </div>
                      <div class="order-oth-item">
                        <span>案件区域</span>${res.body.province +"/" + res.body.city}
                      </div>
                      <div class="order-oth-item">
                        <span>订单编号</span>${res.body.orderId}
                      </div>
                      <div class="order-oth-item">
                        <span>支付时间</span>${res.body.payTime}
                      </div>
                      
                    </div>
                  </div>
          `
          $(".far-right-panel .far-order-info").html(str)

          //如果res.body.lawyerFinish为1的话隐藏倒计时和结束服务
          if(res.body.lawyerFinish == 1){
            $(".zx-time-cutdown").addClass("hide");
            if($(".orderTips").hasClass('hide')){
              $(".orderTips").removeClass('hide')
            }
          }else{
            $(".orderTips").addClass('hide')
          }


          //设置服务时间
          if(res.body.continueTime && res.body.lawyerFinish != 1){
            $("#zxTimeCutdown .zx-time-cutdown-time").text(formatSeconds(res.body.continueTime))
            YX.fn.serveceConsultTime = setInterval(()=>{
              // if(parseInt(res.body.continueTime) > 1800 && $("#endserviceBtn").hasClass("hide")){
              //   $("#endserviceBtn").removeClass("hide")
              // }
              YX.fn.tuWenTimes = res.body.continueTime++;
              $("#zxTimeCutdown .zx-time-cutdown-time").text(formatSeconds(YX.fn.tuWenTimes))
            },1000)
          }
          
        }else{//表示订单已经结束或是其他状态
          _that.noOrderInfo()
        }
      }else{
        _that.noOrderInfo()
      }
  },function(res){
    console.log("错误订单===",res)
  },'lawyerConsult');
}

//暂无订单
YX.fn.noOrderInfo = function(){
  $(".zx-time-cutdown").addClass('hide')
  let str = `
            <div class="no-order-info">
            <img src="./images/flzx/no_order.png" alt="暂无订单"/>
            <div class="no-order-tips">
              <div>暂无进行中订单</div>
              <div class="no-order-end-time">截止到今日：${timetrans(new Date(),'day')}</div>
            </div>
          </div>
  `
  $(".far-right-panel .far-order-info").html(str)
}


/**
 * 导航圆点显示
 */
YX.fn.doPoint = function() {
  var $container;
  var that = this;
  if (!this.$sessionsWrap.is('.hide')) {
    $container = this.$sessionsWrap;
  } else if (!this.$friendsWrap.is('.hide')) {
    $container = this.$friendsWrap;
  } else {
    $container = this.$teamsWrap;
  }
  var $li = $container.find('.m-panel li');
  var $active = $li.map(function() {
    $(this).removeClass('active');
    if ($(this).attr('data-account') == that.crtSessionAccount) {
      $(this).addClass('active');
      return this;
    }
  });
  if ($active.length) {
    var top = $active.offset().top - $container.offset().top + 110;
    // this.$chatVernier.css('top', top).removeClass('hide');
  } else {
    // this.$chatVernier.addClass('hide');
  }
};
//获取好友备注名或者昵称
YX.fn.getNick = function(account) {
  // 使用util中的工具方法
  return getNick(account, this.cache);
};

/*YX.fn.getLastCanShowMsgForInfoProvider = function(lastMsg){
    if (!lastMsg) return;
    var sessionId = lastMsg.sessionId;
    var msgs = this.cache.getMsgs(sessionId);
    var msg;
    for(var i = msgs.length - 1; i >= 0; i--) {
        msg = msgs[i];
        if(msg && (!msg.attach || msg.attach.netcallType === undefined)) {
            break;
        }
    }
    return msg;
}*/
/**
 * 列表项内容提供方法（用于ui组件）
 * @param  {Object} data 数据
 * @param  {String} type 类型
 * @return {Object} info 需要呈现的数据
 */
YX.fn.infoProvider = function(data, type) {
  var info = {};
  switch (type) {
    case 'session':
      var msg = data.lastMsg || {};
      // console.log("==============",msg)
      if (!msg) {
        return;
      }
      var scene = msg.scene;
      info.scene = scene;
      info.account = msg.target;
      info.target = msg.scene + '-' + msg.target;
      info.time = transTime2(msg.time);
      info.crtSession = this.crtSession;
      info.unread = data.unread > 99 ? '99+' : data.unread;
      info.text = buildSessionMsg(msg);
      if (scene === 'p2p') {
        //点对点
        if (msg.target === userUID) {
          info.nick = '我的手机';
          info.avatar = 'images/myPhone.png';
        } else {
          var userInfo = this.cache.getUserById(msg.target);
          info.nick = this.getNick(msg.target);
          info.avatar = getAvatar(userInfo.avatar);
        }
      } else if(scene === 'team') {
        //群组
        var teamInfo = this.cache.getTeamById(msg.target);
        // console.log("==============",teamInfo)
        if (teamInfo) {
          info.nick = teamInfo.name;
          if(teamInfo.serverCustom){
            var teamNameKey = JSON.parse(teamInfo.serverCustom).teamNameKey;
            info.teamNameKey = teamNameKey?teamNameKey:"赢";
          }else{
            info.teamNameKey = "赢";
          }
          if (teamInfo.avatar) {
            info.avatar =
              teamInfo.avatar + '?imageView&thumbnail=40x40&quality=85';
          } else {
            info.avatar = 'images/' + teamInfo.type + '.png';
          }
        } else {
          info.nick = msg.target;
          info.avatar = 'images/normal.png';
        }
      }
      break;
    case 'friend':
      info.target = 'p2p-' + data.account;
      info.account = data.account;
      info.nick = this.getNick(info.account);
      info.avatar = getAvatar(data.avatar);
      info.crtSession = this.crtSession;
      break;
    case 'team':
      info.type = data.type;
      info.nick = data.name;
      info.target = 'team-' + data.teamId;
      info.teamId = data.teamId;
      if(data.serverCustom){
        var teamNameKey = JSON.parse(data.serverCustom).teamNameKey;
        info.teamNameKey = teamNameKey?teamNameKey:"赢";
      }else{
        info.teamNameKey = "赢";
      }
      if (data.avatar) {
        info.avatar = data.avatar + '?imageView&thumbnail=40x40&quality=85';
      } else {
        info.avatar =
          info.type === 'normal' ? 'images/normal.png' : 'images/advanced.png';
      }
      info.crtSession = this.crtSession;
      break;
  }
  return info;
};
/**********************************
 * 登出
 **********************************/
YX.fn.logoutEvt = function() {
  this.$logout = $('#logout');
  this.$logoutDialog = $('#logoutDialog');
  this.$logout.on('click', this.showLogoutDialog.bind(this));
  // this.$logoutDialog.delegate(
  //   '.j-close',
  //   'click',
  //   this.hideLogoutDialog.bind(this)
  // );
  // this.$logoutDialog.delegate('.j-ok', 'click', this.doLogout.bind(this));
};
YX.fn.doLogout = function() {
  sessionStorage.setItem('uid', "");
  sessionStorage.setItem('sdktoken', "");
  sessionStorage.setItem('userId',"");
  sessionStorage.setItem('sessionId',"");
  sessionStorage.setItem('iMmobileNo',"");
  window.location.href = './login.html';
};

//显示退出弹框
YX.fn.showLogoutDialog = function() {
  // $('.firefly_block').addClass("hide");
  // this.$logoutDialog.removeClass('hide');
  // this.$mask.removeClass('hide');
  var that = this;
  window.minAlert.alert({
    type: 'warnning',
    title:"退出登录",
    msg:"确定要退出赢火虫云信网页版吗？",
    cancelBtnMsg: '取消', //取消按钮的按钮内容
    confirmBtnMsg:'确定', //确定按钮的按钮内容
    showConfirm:true,
    cbConfirm: function(){
      $('.firefly_block').addClass("hide");
      that.doLogout();
    }
  });


};

// YX.fn.hideLogoutDialog = function() {
//   this.$logoutDialog.addClass('hide');
//   this.$mask.addClass('hide');
// };

/**********************************************
 * 多端登录管理
 ********************************************/
YX.fn.multiportEvt = function() {
  this.$devices = $('#devices');
  // 踢人 0：移动端 1：pc端
  $('#devices .mobile .j-kickMoblie').on(
    'click',
    function() {
      this.mysdk.kick(0);
    }.bind(this)
  );
  $('#devices .pc .j-kickPc').on(
    'click',
    function() {
      this.mysdk.kick(1);
    }.bind(this)
  );
  $('#backBtn2').on('click', this.hideDevices.bind(this));
  // $('.m-devices').on('click', this.showDevices.bind(this));
};
//SDK回调
(YX.fn.loginPorts = function(devices) {
  var pc, mobile;
  for (var i = devices.length - 1; i >= 0; i--) {
    if (/iOS|Android|WindowsPhone/i.test(devices[i].type)) {
      mobile = devices[i];
    } else if (/Mac|PC/i.test(devices[i].type)) {
      pc = devices[i];
    }
  }
  if ((pc && pc.online) || (mobile && mobile.online)) {
    if (pc && pc.online && (mobile && mobile.online)) {
      // $('.m-devices').html('正在使用赢火虫云信手机版，电脑版');
      $('#devices .pc').removeClass('hide');
      $('#devices .mobile').removeClass('hide');
      this.mysdk.mobileDeviceId = mobile.deviceId;
      this.mysdk.pcDeviceId = pc.deviceId;
    } else if (pc && pc.online) {
      // $('.m-devices').html('正在使用赢火虫云信电脑版');
      $('#devices .pc').removeClass('hide');
      $('#devices .mobile').addClass('hide');
      this.mysdk.mobileDeviceId = false;
      this.mysdk.pcDeviceId = pc.deviceId;
    } else {
      // $('.m-devices').html('正在使用赢火虫云信手机版');
      $('#devices .mobile').removeClass('hide');
      $('#devices .pc').addClass('hide');
      this.mysdk.mobileDeviceId = mobile.deviceId;
      this.mysdk.pcDeviceId = false;
    }
    // $('.m-devices').removeClass('hide');
    // $('#left-panel .item').height(456);
    // $('#chatVernier').css({ marginTop: '41px' });
  } else {
    // $('.m-devices').addClass('hide');
    $('#devices').addClass('hide');
    $('#devices .pc').addClass('hide');
    $('#devices .mobile').addClass('hide');
    this.mysdk.mobileDeviceId = false;
    this.mysdk.pcDeviceId = false;
    // $('#left-panel .item').height(456);
    // $('#chatVernier').css({ marginTop: '0' });
  }
}),
  /**
   * 多端登录面板UI
   */
  (YX.fn.showDevices = function() {
    this.$devices.removeClass('hide');
  });
YX.fn.hideDevices = function() {
  this.$devices.addClass('hide');
};
/**
 * 语音播放
 */
YX.fn.playAudio = function() {
  // 点击音频则停止录音
  YX.fn.stopRecordAudio()
  var node = $(this);
  if (!node.hasClass('u-audio')) {
    node = node.parent()
  }
  var btn = node && node.children('.j-play');
  var sameNode = node.hasClass('play')
  YX.fn.stopPlayAudio()
  if (sameNode) {
    return
  }
  YX.fn.playAudio.$audio = {
    node: node,
    audio: document.createElement('audio')
  };
  var $audio = YX.fn.playAudio.$audio.audio
  var $source = document.createElement('source');
  var audioType = btn.attr('data-ext');
  $source.src = btn.attr('data-src');
  $source.type = 'audio/' + (audioType === 'mp3' ? 'mpeg' : audioType);
  $audio.appendChild($source)
  $audio.play()
  node.addClass('play');
  setTimeout(function() {
    node.removeClass('play');
  }, parseInt(btn.attr('data-dur')));
  if (node.hasClass('unreadAudio') && btn.attr('data-id')) {
    nim.updateLocalMsg({
      idClient: btn.attr('data-id'),
      localCustom: '{"audio": "played"}'
    });
    node.removeClass('unreadAudio');
    $audio.onended = YX.fn.autoPlayNextUnreadAudio
  }
};
YX.fn.stopPlayAudio = function() {
  if (YX.fn.playAudio.$audio.audio) {
    YX.fn.playAudio.$audio.node.removeClass('play');
    YX.fn.playAudio.$audio.audio.pause();
    YX.fn.playAudio.$audio = {
      node: null,
      audio: null
    };
  }
};
YX.fn.autoPlayNextUnreadAudio = function() {
  var parentNode = YX.fn.playAudio.$audio.node && YX.fn.playAudio.$audio.node.parent()
  if (!parentNode) {
    return
  }
  var currentMsgNode = parentNode.parent().parent().parent();
  var nextMsgNode = currentMsgNode[0].nextElementSibling
  var $nextMsgNode
  var nextAudioNode
  while (nextMsgNode) {
    $nextMsgNode = $(nextMsgNode)
    if ($nextMsgNode.hasClass('item-you')) {
      nextAudioNode = nextMsgNode.querySelector('.u-audio')
      if (nextAudioNode) {
        break
      }
    }
    nextMsgNode = nextMsgNode.nextElementSibling
  }
  if (nextMsgNode && $(nextAudioNode).hasClass('unreadAudio')) {
    nextAudioNode.click()
  }
};
// 播放音频信息使用的 audio
YX.fn.playAudio.$audio = {
  node: null,
  audio: null
}
